package com.example.myspringboot.anno;

import cn.hutool.core.util.IdUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author cy
 * @date 2023/11/30
 */
public class LogInterceptor implements HandlerInterceptor {

    Logger logger = LoggerFactory.getLogger(LogInterceptor.class);

    private static final String LOG_ID_KEY = "logId";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            MDC.put(LOG_ID_KEY, IdUtil.getSnowflakeNextIdStr());
            return true;
        } catch (IllegalArgumentException e) {
            logger.warn(e.getMessage(), e);
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        try {
            MDC.remove(LOG_ID_KEY);
        } catch (IllegalArgumentException e) {
            logger.warn(e.getMessage(), e);
        }
    }
}
